define(function(require, exports, module) {
    'use strict';

    var rk = require('rk');

    require('../statistics/wrStatisticsCtrl');
    require('./wrCommentCtrl');
    require('core/services/2.0/rk_workreportService');
    var uploadUtil = require('core/utils/uploadUtil');
    var rk_userService = require('userService');
    var numberUtil = require('core/utils/numberUtil');

    $.widget('rk.wrDetailCtrl', {
        detailCon: null,
        isSingle: false, //is single page
        _create: function() {
            var me = this;
            var elem = me.element;
            if (me.options.act == 'single') me.isSingle = true;
        },
        defaultOffset: null,
        _init: function() {
            var me = this;
            var elem = me.element;
            me.detailCon = elem.find('.task_right_detail_inner');
            me.defaultOffset = elem.offset();
        },
        currentId: null,
        getCurrentId: function() {
            var me = this;
            return me.currentId;
        },
        currencyUnit: '元',
        loadData: function(reportId, ownerId, succFn, errorFn) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            if (typeof succFn == 'undefined') succFn = function() {};
            if (typeof errorFn == 'undefined') errorFn = function() {};
            me.clean();
            me.showLoading();
            var url = '/json/oa_workreport/detail.action';

            $.ajax({
                    url: url,
                    data: {
                        reportId: reportId
                            //,pageUserId: ownerId
                    },
                    dataType: 'json',
                    type: 'POST'
                }).success(function(data) {
                    if (!data) return;
                    if (data.status == 314003) {
                        var html = rk.templateText(require('oa/tmpl/workreport/tpl_workreport_error_tip.tpl'), {
                            errorMsg: rk.i18n('WORKREPORT_NOT_EXIST')
                        });
                        elem.html(html);
                        return;
                    }
                    if (data.status !== 0) {
                        (errorFn)(data.status);
                        return;
                    }

                    data = data.data;
                    if (!data.entity) return;
                    if (data.businessTypes) {
                        workreportService.cacheBelongTypeIds(data.businessTypes);
                    }
                    if (data.users) {
                        rk_userService.appendUserInfo(data.users);
                    }
                    me.currentId = reportId;
                    me.currencyUnit = data.currencyUnit;
                    workreportService.setCurrencyUnit(me.currencyUnit);
                    var entity = data.entity;
                    var html = me._getHtml(data);
                    var isDraft = (entity.draft == '1');
                    var entitytype = entity.type;
                    me.detailCon.html(html);
                    me._showStatics(data);

                    elem.find('[act="editWorkreport"]').click(function() {
                        var info = workreportService.getBelongType(entitytype);
                        me._popupEditor(entity.id, info);
                    });
                    elem.find('.delete').click(function() {
                        workreportService.deleteReport(reportId, function() {
                            rk.oa.closeContent();
                            //$('#taskDetailDiv').wrDetailCtrl('clean');
                            var panel = rk.oa.getPanel();
                            var searchBox = panel.find('.oa-curtain-body .oa-search-table');
                            if (searchBox.is(':visible')) {
                                searchBox.find('a[act="adv-search-btn"]').click();
                            } else {
                                panel.find('.oa-tab-header:visible a.active').click();
                            }

                            //me.clean();
                            //me._trigger("onDeleteSucc", null/*event*/, {});
                        });
                    });
                    if (!isDraft)
                        elem.find('.comment_container').wrCommentCtrl({
                            reportId: reportId,
                            isApproved: (entity.status == '2'),
                            listId: opt.listId,
                            recipientIsMe: (entity.recipient == SESSION.user.id)
                        });
                    if (typeof succFn != 'undefined')(succFn)();
                })
                .error(function() {
                    (errorFn)(null);
                })
                .complete(function() {});
        },
        _popupEditor: function(reportId, info) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            workreportService.popupEditor({
                editorAct: 'edit',
                reportId: reportId,
                editorType: info.alias,
                belongTypeId: info.id
            });
        },
        _showStatics: function(data) {
            var me = this;
            var elem = me.element;
            if (!data.entity) return;
            var entity = data.entity;
            var con = elem.find('.detail_sales_data');

            var start = moment(parseFloat(entity.date));

            var belongTypeId = entity.type;
            var type;
            if (me.options.editorType) {
                type = me.options.editorType;
            } else if (me.currentEntity) {
                var info = workreportService.getBelongType(belongTypeId);
                type = info.alias;
            }
            con.wrStatisticsCtrl({
                currentEntity: me.currentEntity,
                belongTypeId: belongTypeId,
                currencyUnit: data.currencyUnit
            });
            var belongTypeId = entity.type;
            var belongTypeInfo = workreportService.getBelongType(belongTypeId);
            var typeAlias = belongTypeInfo.alias;
            var showStatistics = workreportService.shouldShowStatistics(data);
            if (showStatistics) {
                con.show();
                con.wrStatisticsCtrl('loadData', typeAlias, me.currentOwnerId, start);
            } else {
                con.hide();
            }
        },
        clean: function() {
            var me = this;
            var elem = me.element;
            me.currentId = null;
            me.detailCon.html('<div class="daily_detail_none"></div>');
        },
        currentEntity: null,
        currentOwnerId: null,
        _getHtml: function(data) {
            var me = this;
            if (!data.entity) return;
            var entity = data.entity ? data.entity : {};
            var ownerId = entity.updatedBy; //提交人
            entity.ownerInfo = rk_userService.getUserInfo(ownerId);
            me.currentOwnerId = ownerId;
            var recipientId = data.recipient; //批阅人
            entity.recipientInfo = rk_userService.getUserInfo(recipientId);
            entity.createdAtText = entity.timeLine; //创建时间
            entity.updatedAtText = moment(parseFloat(entity.updatedAt)).format('YYYY-MM-DD'); //批阅时间
            entity = workreportService.getBooleanStatus(entity);
            var belongTypeId = entity.type;
            var belongId = me._getBelongid(belongTypeId, data.businessTypes);
            entity.belongText = workreportService.getBelongidText(belongId);
            entity.belongName = workreportService.getTypeByBelongid(belongId);
            entity.dateText = workreportService.getDateTitle(moment(parseFloat(entity.date)), entity.belongName); // moment(parseFloat(entity.date)).format('YYYY-MM-DD');//报告所指的时间

            entity.belongTypeId = belongTypeId;
            entity.isDraft = (entity.draft === '1');
            entity.newFileUrl = workreportService.getDownloadUrl(entity.id); //'/json/sns_work_report/download.action?reportId=' + entity.id;

            entity.hasCcUsers = false;
            if (entity.copyTo) {
                var users = me._getCopyUsers(entity);
                entity.hasCcUsers = (users.length > 0 ? true : false);
                entity.ccUsers = users;
            }
            entity.hasAttachment = (entity.fileName ? true : false);
            if (entity.hasAttachment) {
                var arr = entity.fileName.split('.');
                var fileType = '.' + arr[arr.length - 1];
                entity.fileIcon = uploadUtil.getIconClass(fileType);
            }

            data.customizedData = me._getCustomizedData(data);
            //template.config('escape', false);//不替换html字符

            var approvedHtml = rk.templateText(require('oa/tmpl/workreport/asset/detailTemplate_approved.tpl'), entity);
            var headerHtml = rk.templateText(require('oa/tmpl/workreport/asset/detailTemplate_header.tpl'), entity)
            var staticsHtml = rk.templateText(require('oa/tmpl/workreport/asset/detailTemplate_statics.tpl'), {})
            var customizedHtml = rk.templateText(require('oa/tmpl/workreport/asset/detailTemplate_customized.tpl'), data)
            var contentHtml = rk.templateText(require('oa/tmpl/workreport/asset/detailTemplate_content.tpl'), entity)




            me.currentEntity = $.extend(true, {}, entity); //cache

            return (entity.isRead ? approvedHtml : '') + headerHtml + staticsHtml + '<div class="task_detail_content daily_detail_content right_report_detail">' + '<div class="task_tip_content">' + '<div class="detail_field">' + customizedHtml + contentHtml + '</div>' + '</div>' + '</div>';
        },
        _getCopyUsers: function(entity) {
            var str = entity.copyTo;
            var arr = str.split(',');
            var users = [];
            for (var i = 0; i < arr.length; i++) {
                var userid = $.trim(arr[i]);
                var userInfo = rk_userService.getUserInfo(userid);
                users.push(userInfo);
            }
            return users;
        },
        _getBelongid: function(typeId, businessTypes) {
            var belongId;
            for (var i = 0; i < businessTypes.length; i++) {
                var bt = businessTypes[i];
                bt.id = bt.id + '';
                if (bt.id == typeId) return bt.belongId + '';
            }
        },
        _helperCache: {},
        _getCustomizedData: function(data) {
            var me = this;
            var entity = data.entity;
            var items = data.items;
            if (!entity || !items || items.length == 0) return [];
            var resultData = [];
            var _content, _plan;
            for (var i = 0, len = items.length; i < len; i++) {
                var item = items[i];
                var key = item.entryPropertyNameOnly;
                var data = me._getOneCustomizedData(item, entity);
                //if(key != 'content' && key != 'plan'){
                resultData.push(data);
                // }else{
                //     if(key == 'content'){_content = data;}
                //     if(key == 'plan'){_plan = data;}
                // }
            }
            //确保显示在最后
            //if(_content)resultData.push(_content);
            //if(_plan)resultData.push(_plan);
            return resultData;
        },
        _getOneCustomizedData: function(item, entity) {
            var me = this;
            var searchType = item.searchType;
            var key = item.entryPropertyNameOnly;
            var value = entity[key];
            var isCurrency = (item.currencyFlg === 1);
            var text;
            if ((!$.isArray(value) && value) || ($.isArray(value) && value.length > 0)) {
                text = me._getDisplayText(searchType, value, item);
            } else {
                text = null;
            }
            var data = {
                itemName: item.itemName + (isCurrency ? '(' + me.currencyUnit + ')' : ''),
                value: value,
                text: text,
                key: key
            };
            return data;
        },
        _getDisplayText: function(searchType, value, helper) {
            //取自admin页面
            // <option value="1" 文本</option>
            // <option value="2" 单选</option>
            // <option value="3" 多选</option>
            // <option value="4" 文本域</option>
            // <option value="5" 整数</option>
            // <option value="6" 实数</option>
            // <option value="7" 日期</option>
            // <option value="8" 分割线</option>
            // <option value="9" 自动编号</option>
            searchType = searchType + '';
            var text = value;
            switch (searchType) {
                case '3': //单选
                    var options = helper.options;
                    for (var i = 0, len = options.length; i < len; i++) {
                        var opt = options[i];
                        if (opt.id == value) text = opt.name;
                    }
                    break;
                case '4': //多选
                    var options = helper.options;
                    var map = {};
                    for (var i = 0, len = options.length; i < len; i++) {
                        var opt = options[i];
                        map[opt.id] = opt.name;
                    }
                    var arr = [];
                    for (var i = 0, len = value.length; i < len; i++) {
                        var val = value[i];
                        var text = map[val];
                        arr.push(text);
                    }
                    text = arr.join('、');
                    break;
                case '6':
                    text = numberUtil.formatAsCurrency(text);
                    break;
                case '7':
                    text = moment(parseFloat(value)).format('YYYY-MM-DD');
                    break;
                default:

            }
            if (text) {
                text = $.htmlDecode(text).replace(/\n/g, '<br/>');
            }
            return text;
        },
        showTextOfApproved: function() {
            var me = this;
            var elem = me.element;
            var userName = rk_userService.getUserInfo(SESSION.user.id).name;

            var html = require('oa/tmpl/workreport/asset/detailTemplate_approved.tpl');
            var approvedHtml = rk.templateText(html, {
                updatedAtText: moment().format('YYYY-MM-DD'),
                recipientInfo: {
                    name: userName
                }
            });
            // template('detailTemplate_approved', {
            //    updatedAtText: moment().format('YYYY-MM-DD'),
            //    recipientInfo: {
            //        name: userName
            //    }
            //});
            $(approvedHtml).insertBefore(me.detailCon.find('.task_detail_head'));
        },
        getCurrentEntity: function() {
            var me = this;
            return me.currentEntity;
        },
        showLoading: function() {
            var me = this;
            var elem = me.element;
            me.detailCon.html('<div class="loading face_load hidden" style="display: block;"><span>' + rk.i18n('WORKREPORT_LOADING') + '</span></div>');
        },
        showNoData: function() {
            var me = this;
            var elem = me.element;
            me.detailCon.html(rk.i18n('WORKREPORT_NO_DATA_OR_FAILURE'));
        }
    });
});
